package de.uni_mannheim.informatik.ai.dame_ai.main.ui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

import de.uni_mannheim.informatik.ai.dame_ai.main.application.GameProperty;
import de.uni_mannheim.informatik.ai.dame_ai.main.application.GameSettings;
import de.uni_mannheim.informatik.ai.dame_ai.main.application.MainPlayer;
import de.uni_mannheim.informatik.ai.dame_ai.main.ui.MainMenuDictionary.Phrases;



public class ChoosePlayerPanel extends ObservablePanel implements TableModelListener{
	GameProperty properties;
	GameSettings settings;
	BufferedImage hook;
	public ChoosePlayerPanel(int width, int height,GameProperty properties, File imagePath, GameSettings settings){
		super(width,height,imagePath);
		this.properties = properties;
		this.settings = settings;
		mainDict = MainMenuDictionary.getDictionary(settings.getLanguage());
		this.langButton.setText(mainDict.translate(Phrases.main_language));
		try {
			hook = ImageIO.read(new File("media/main/hook.png"));
		} catch (IOException e) {
		}
		//setSize(width, height);
		//this.setBackground(Color.BLUE);
		//setLayout(new GridLayout(5,0));
		insertPlayerSlots(properties.getMaxPlayers());
		setPaneLayout(null);
	}
	JTable table;
	Object[][] data;
	JScrollPane scrollPane;
	JButton buttonWithHook;
	JButton buttonReturn;
	public void calculateGeneralBounds(){
		super.calculateGeneralBounds();
		pane.remove(scrollPane);
		pane.remove(buttonWithHook);
		pane.remove(buttonReturn);
		insertPlayerSlots(properties.getMaxPlayers());
	}
	private void insertPlayerSlots(int playerSlots){
		MainPlayer[] players = settings.getPlayers();
		if(settings.getPlayers()==null){
			data = new Object[playerSlots][3];
			for(int i =0; i<playerSlots;i++){
				data[i][0]=new Integer(i);
				data[i][1]=mainDict.translate(Phrases.main_name);
				data[i][2]=new Boolean(true);
			}
		}	
		else {
			data = new Object[players.length][3];
			for(int i = 0; i<players.length;i++){
				data[i][0]=players[i].getNumber();
				data[i][1]=players[i].getName();
				data[i][2]=players[i].isHuman();
			}
		}
		table = new JTable(new MyTableModel(data));
        table.setPreferredScrollableViewportSize(new Dimension(getWidth(), getHeight()));
        table.setFillsViewportHeight(true);
        //Create the scroll pane and add the table to it.
        scrollPane = new JScrollPane(table);
        table.setFillsViewportHeight(true);
        scrollPane.setMinimumSize(new Dimension(getWidth(),130));
        scrollPane.setBounds(getWidth()/5*3, 0, getWidth()/5*2, getHeight());
        //scrollPane.setMaximumSize(new Dimension(getWidth(),70));
        //Add the scroll pane to this panel.
        addToPane(scrollPane);
        buttonWithHook = addAButton(hook);
        buttonWithHook.setText(mainDict.translate(Phrases.main_ok));
        buttonWithHook.setBounds(getWidth()/5*2, getHeight()/15, getWidth()/6, getHeight()/15);
        buttonReturn = addAButton(returnImg);
        buttonReturn.setText(mainDict.translate(Phrases.main_return));
        buttonReturn.setBounds(getWidth()/5*2, getHeight()/15*3, getWidth()/6, getHeight()/15);
        buttonReturn.addActionListener(new ReturnButtonListener());
        addToPane(buttonWithHook);
        addToPane(buttonReturn);
	}
	@Override
	public void paint(Graphics g) {
		//scrollPane.setMinimumSize(new Dimension(getWidth(),70));
		//stable.setBounds(new Rectangle(5,5,))
		super.paint(g);
		
		
	}
	public void setFrameReference(JFrame frame){
		this.frameReference = frame;
	}
	private JButton addAButton(Image icon) {
        JButton button = new JButton();
        button.addActionListener(new ButtonListener());
        button.setIcon(new ImageIcon(getScaledImage(icon, getHeight()/12, getHeight()/12)));
        button.setBorder(compound);
        
        button.setAlignmentX(Component.CENTER_ALIGNMENT);
        return button;
    }
	@Override
	public void tableChanged(TableModelEvent e) {
        int row = e.getFirstRow();
        int column = e.getColumn();
        TableModel model = (TableModel)e.getSource();
        String columnName = model.getColumnName(column);
        Object data = model.getValueAt(row, column);

        this.data[row][column]=data;
    }
	class ButtonListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent button) {
			MainPlayer[] players = new MainPlayer[data.length];
			for(int i = 0;i<data.length;i++){
				MainPlayer player = new MainPlayer();
				player.setNumber((Integer)data[i][0]);
				player.setName((String)data[i][1]);
				player.setHuman((Boolean)data[i][2]);
				players[i]=player;
				
			}
			int humans=0;
			for(MainPlayer temp : players){
				if(temp.isHuman())humans++;
			}
			if(humans>=properties.getMinHumanPlayers()){
				observableObject.setResult(players);
				observableObject.notifyObservers();
			} else {
				JOptionPane.showMessageDialog(null, mainDict.translate(Phrases.main_noHuman), mainDict.translate(Phrases.main_error), JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {mainDict.translate(Phrases.main_number),
        		mainDict.translate(Phrases.main_name),
        		mainDict.translate(Phrases.main_human)};
        private Object[][] data;
        public MyTableModel(Object[][] data){
        	this.data = data;
        }
        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
         */
        public Class getColumnClass(int c) {
            System.out.println("column: "+c);
        	Class typeClass = getValueAt(0, c).getClass();
        	System.out.println(typeClass);
        	//printDebugData();
        	return typeClass;
        }

        /*
         * Don't need to implement this method unless your table's
         * editable.
         */
        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();

            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + data[i][j]);
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }

        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col < 1) {
                return false;
            } else {
                return true;
            }
        }

        /*
         * Don't need to implement this method unless your table's
         * data can change.
         */
        public void setValueAt(Object value, int row, int col) {

            data[row][col] = value;
            fireTableCellUpdated(row, col);

        }
    }
	
	class ReturnButtonListener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent button) {
			((MainMenuFrame)frameReference).doOnReturnButtonClicked("ChoosePlayerPanel");
		}
	}
}